package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.core.model.Teacher;
import com.geyue.core.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Lyon on 2017/4/24.
 */
@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return "error";

        model.addAttribute("info",teacherService.getOneByKey(teacher.getId()));
        return "teacher_info";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return "error";

        model.addAttribute("info",teacherService.getOneByKey(teacher.getId()));
        return "teacher_edit";
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @ResponseBody
    public Res edit(Teacher teacher, HttpSession session) {

        if(teacherService.updateNotEmpty(teacher) > 0)
            return Res.success("修改成功!");

        return Res.fail("修改失败");
    }

    @RequestMapping(value = "/password", method = RequestMethod.GET)
    public String password(Model model,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        if(teacher == null)
            return "error";

        return "teacher_password";
    }


    @RequestMapping(value = "/password", method = RequestMethod.PUT)
    @ResponseBody
    public Res password(String password,String newPass,HttpSession session) {
        Teacher teacher = (Teacher) session.getAttribute("teacher");

        Teacher t1 = teacherService.getOneByKey(teacher.getId());

        if(t1.getPassword().equals(password)){
            Teacher param = new Teacher();
            param.setId(teacher.getId());
            param.setPassword(newPass);
            if(teacherService.updateNotEmpty(param) > 0)
                return Res.success("修改成功");
        }

        return Res.fail("修改失败!");
    }

}
